/**
 * 熵巡 - 企业级氚云OpenAPI数据管理平台
 * 开发归属 Alyr.net
 * 处理管理员账号修改功能
 * 尊重劳动成果是一种美德
 */


// 显示用户配置弹窗
function showUserConfigModal() {
    console.log('显示用户配置弹窗');
    
    // 获取当前用户配置
    fetch('api/get_user_config.php')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 填充表单
                document.getElementById('modal-username').value = data.data.username || '';
                document.getElementById('modal-password').value = '';
                document.getElementById('modal-confirm-password').value = '';
                document.getElementById('modal-phone').value = data.data.phone || '';
                document.getElementById('modal-dingtalk-id').value = data.data.dingtalk_id || '';
                document.getElementById('modal-wechat-id').value = data.data.wechat_id || '';
                document.getElementById('modal-feishu-id').value = data.data.feishu_id || '';
            } else {
                console.error('获取用户配置失败:', data.message);
                // 使用默认值
                document.getElementById('modal-username').value = 'admin';
                document.getElementById('modal-password').value = '';
                document.getElementById('modal-confirm-password').value = '';
                document.getElementById('modal-phone').value = '';
                document.getElementById('modal-dingtalk-id').value = '';
                document.getElementById('modal-wechat-id').value = '';
                document.getElementById('modal-feishu-id').value = '';
            }
            
            // 根据插件启用状态设置必填
            updateRequiredFields();
            
            // 显示弹窗
            document.getElementById('userConfigModal').style.display = 'flex';
        })
        .catch(error => {
            console.error('获取用户配置出错:', error);
            // 使用默认值并显示弹窗
            document.getElementById('modal-username').value = 'admin';
            document.getElementById('modal-password').value = '';
            document.getElementById('modal-confirm-password').value = '';
            document.getElementById('modal-phone').value = '';
            document.getElementById('modal-dingtalk-id').value = '';
            document.getElementById('modal-wechat-id').value = '';
            document.getElementById('modal-feishu-id').value = '';
            
            // 根据插件启用状态设置必填
            updateRequiredFields();
            
            document.getElementById('userConfigModal').style.display = 'flex';
        });
}

// 根据插件启用状态更新必填项
function updateRequiredFields() {
    // 获取插件配置
    fetch('api/get_user_config.php')
        .then(response => response.json())
        .then(data => {
            if (data.success && data.plugins) {
                const phoneInput = document.getElementById('modal-phone');
                const dingtalkInput = document.getElementById('modal-dingtalk-id');
                const wechatInput = document.getElementById('modal-wechat-id');
                
                // 短信登录启用，手机号必填
                if (data.plugins.sms && data.plugins.sms.enabled) {
                    phoneInput.setAttribute('required', 'required');
                } else {
                    phoneInput.removeAttribute('required');
                }
                
                // 钉钉登录启用，钉钉号必填
                if (data.plugins.dingtalk && data.plugins.dingtalk.enabled) {
                    dingtalkInput.setAttribute('required', 'required');
                } else {
                    dingtalkInput.removeAttribute('required');
                }
                
                // 微信登录启用，微信号必填
                if (data.plugins.wechat && data.plugins.wechat.enabled) {
                    wechatInput.setAttribute('required', 'required');
                } else {
                    wechatInput.removeAttribute('required');
                }
                
                // 飞书登录启用，飞书号必填
                const feishuInput = document.getElementById('modal-feishu-id');
                if (data.plugins.feishu && data.plugins.feishu.enabled) {
                    feishuInput.setAttribute('required', 'required');
                } else {
                    feishuInput.removeAttribute('required');
                }
            }
        })
        .catch(error => {
            console.error('获取插件配置失败:', error);
        });
}

// 隐藏用户配置弹窗
function hideUserConfigModal() {
    console.log('隐藏用户配置弹窗');
    document.getElementById('userConfigModal').style.display = 'none';
    
    // 清空表单
    document.getElementById('userConfigForm').reset();
}

// 保存用户配置
function saveUserConfig() {
    console.log('保存用户配置');
    
    const username = document.getElementById('modal-username').value.trim();
    const password = document.getElementById('modal-password').value;
    const confirmPassword = document.getElementById('modal-confirm-password').value;
    const phone = document.getElementById('modal-phone').value.trim();
    const dingtalkId = document.getElementById('modal-dingtalk-id').value.trim();
    const wechatId = document.getElementById('modal-wechat-id').value.trim();
    const feishuId = document.getElementById('modal-feishu-id').value.trim();
    
    // 表单验证
    if (!username) {
        alert('请输入用户名');
        return;
    }
    
    if (!password) {
        alert('请输入密码');
        return;
    }
    
    if (password !== confirmPassword) {
        alert('两次输入的密码不一致');
        return;
    }
    
    if (password.length < 3) {
        alert('密码长度不能少于3个字符');
        return;
    }
    
    // 验证手机号格式（如果填写了）
    if (phone && !/^1[3-9]\d{9}$/.test(phone)) {
        alert('手机号码格式不正确');
        return;
    }
    
    // 创建表单数据
    const formData = new FormData();
    formData.append('username', username);
    formData.append('password', password);
    formData.append('phone', phone);
    formData.append('dingtalk_id', dingtalkId);
    formData.append('wechat_id', wechatId);
    formData.append('feishu_id', feishuId);
    
    // 发送保存请求
    fetch('api/save_user_config.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('用户配置保存成功！请重新登录。');
            // 隐藏弹窗
            hideUserConfigModal();
            // 退出登录
            window.location.href = 'logout.php';
        } else {
            alert('保存失败: ' + (data.message || '未知错误'));
        }
    })
    .catch(error => {
        console.error('保存用户配置出错:', error);
        alert('保存失败，请重试');
    });
}

// 点击弹窗背景关闭弹窗
document.addEventListener('DOMContentLoaded', function() {
    const modal = document.getElementById('userConfigModal');
    if (modal) {
        modal.addEventListener('click', function(e) {
            if (e.target === modal) {
                hideUserConfigModal();
            }
        });
    }
    
    // ESC键关闭弹窗
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape' && modal.style.display === 'flex') {
            hideUserConfigModal();
        }
    });
});